import 'package:mobx/mobx.dart';
import 'package:thal/backstage/blueprint/dynamic_print.dart';

part 'dynamic_room.g.dart';

/// 动态状态管理
class DynamicRoom = _DynamicRoom with _$DynamicRoom;

abstract class _DynamicRoom with Store {
  /// 动态列表
  @observable
  ObservableList<DynamicPrint> dynamics = ObservableList<DynamicPrint>();

  /// 初始化默认动态数据
  @action
  void initializeDefaultDynamics() {
    dynamics.clear();
    dynamics.addAll([
      // 图片动态 1 - 单张图片
      DynamicPrint(
        id: '1',
        userId: '8', // admin用户
        title: 'Sunset Magic at Lake Tahoe',
        content:
            'Beautiful sunset at Lake Tahoe! The colors are absolutely stunning today. 🌅',
        mediaUrls: ['assets/images/dongtai1.png', 'assets/images/dongtai2.png'],
        mediaType: 'image',
        thumbnailUrls: [],
        createdAt: DateTime.now().subtract(const Duration(hours: 2)),
        likes: ['2', '3', '4'],
        comments: [
          DynamicComment(
            id: '1',
            userId: '2',
            content: 'Amazing shot! The colors are incredible!',
            createdAt: DateTime.now().subtract(const Duration(hours: 1)),
          ),
          DynamicComment(
            id: '2',
            userId: '3',
            content: 'I wish I was there right now! 😍',
            createdAt: DateTime.now().subtract(const Duration(minutes: 30)),
          ),
        ],
      ),

      // 视频动态 1 - 单个视频
      DynamicPrint(
        id: '2',
        userId: '2', // waterlover用户
        title: 'Morning Swim Adventure',
        content:
            'Morning swim in Lake Como! The water is so refreshing and clear. 🏊‍♂️',
        mediaUrls: ['assets/videos/lake_video1.mp4'],
        mediaType: 'video',
        thumbnailUrls: ['assets/images/lake_video1.png'],
        createdAt: DateTime.now().subtract(const Duration(hours: 4)),
        likes: ['1', '3', '5', '6'],
        comments: [
          DynamicComment(
            id: '3',
            userId: '1',
            content: 'Looks so peaceful! I need to visit Lake Como soon.',
            createdAt: DateTime.now().subtract(const Duration(hours: 3)),
          ),
        ],
      ),

      // 图片动态 2 - 多张图片
      DynamicPrint(
        id: '3',
        userId: '1', // lakephoto用户
        title: 'Aerial View of Crater Lake',
        content:
            'Crater Lake from above! The depth and clarity are mind-blowing. 📸',
        mediaUrls: ['assets/images/dongtai3.png', 'assets/images/dongtai4.png'],
        mediaType: 'image',
        thumbnailUrls: [],
        createdAt: DateTime.now().subtract(const Duration(hours: 6)),
        likes: ['1', '2', '4', '7', '8'],
        comments: [
          DynamicComment(
            id: '4',
            userId: '4',
            content: 'Your photography skills are incredible!',
            createdAt: DateTime.now().subtract(const Duration(hours: 5)),
          ),
          DynamicComment(
            id: '5',
            userId: '7',
            content: 'This is now on my bucket list!',
            createdAt: DateTime.now().subtract(const Duration(hours: 2)),
          ),
        ],
      ),

      // 图片动态 3
      DynamicPrint(
        id: '4',
        userId: '4', // naturefan用户
        title: 'Hidden Gem Discovery',
        content:
            'Found this hidden gem today! Sometimes the best lakes are the ones you discover by accident. 🍃',
        mediaUrls: ['assets/images/dongtai5.png', 'assets/images/dongtai6.png'],
        mediaType: 'image',
        thumbnailUrls: [],
        createdAt: DateTime.now().subtract(const Duration(hours: 8)),
        likes: ['2', '3', '5'],
        comments: [
          DynamicComment(
            id: '6',
            userId: '2',
            content: 'Where is this? It looks magical!',
            createdAt: DateTime.now().subtract(const Duration(hours: 7)),
          ),
        ],
      ),

      // 图片动态 4 - 多张图片
      DynamicPrint(
        id: '5',
        userId: '5', // lakeexplorer用户
        title: 'Lake Exploration Journey',
        content:
            'Lake exploration day! Every lake has its own personality and story to tell. 🗺️',
        mediaUrls: ['assets/images/dongtai7.png', 'assets/images/dongtai8.png'],
        mediaType: 'image',
        thumbnailUrls: [],
        createdAt: DateTime.now().subtract(const Duration(hours: 12)),
        likes: ['1', '3', '4', '6', '9'],
        comments: [
          DynamicComment(
            id: '7',
            userId: '6',
            content: 'I love your exploration posts! Keep them coming!',
            createdAt: DateTime.now().subtract(const Duration(hours: 10)),
          ),
        ],
      ),

      // 视频动态 2
      DynamicPrint(
        id: '6',
        userId: '1', // waterdream用户
        title: 'Peaceful Morning Meditation',
        content:
            'Peaceful morning by the lake. Sometimes you just need to sit and listen to the water. 🧘‍♀️',
        mediaUrls: ['assets/videos/lake_video2.mp4'],
        mediaType: 'video',
        thumbnailUrls: ['assets/images/lake_video2.png'],
        createdAt: DateTime.now().subtract(const Duration(hours: 16)),
        likes: ['1', '2', '4', '7', '8', '10'],
        comments: [
          DynamicComment(
            id: '8',
            userId: '7',
            content: 'This is exactly what I needed to see today. So calming!',
            createdAt: DateTime.now().subtract(const Duration(hours: 14)),
          ),
          DynamicComment(
            id: '9',
            userId: '8',
            content: 'Nature therapy at its finest! 🌿',
            createdAt: DateTime.now().subtract(const Duration(hours: 12)),
          ),
        ],
      ),

      // 图片动态 5
      DynamicPrint(
        id: '7',
        userId: '1', // laketravel用户
        title: 'Travel Photography Tips',
        content:
            'Travel tip: Always bring your camera when visiting lakes. You never know what magic you\'ll capture! 📷',
        mediaUrls: [
          'assets/images/dongtai9.png',
          'assets/images/dongtai10.png',
        ],
        mediaType: 'image',
        thumbnailUrls: [],
        createdAt: DateTime.now().subtract(const Duration(hours: 20)),
        likes: ['3', '5', '6', '8'],
        comments: [
          DynamicComment(
            id: '10',
            userId: '8',
            content: 'Great tip! I always forget my camera.',
            createdAt: DateTime.now().subtract(const Duration(hours: 18)),
          ),
        ],
      ),

      // 图片动态 6
      DynamicPrint(
        id: '8',
        userId: '3', // waterpeace用户
        title: 'Nature\'s Mirror',
        content:
            'Lake reflections are like nature\'s mirrors. What do you see in this one? 🌊',
        mediaUrls: [
          'assets/images/dongtai11.png',
          'assets/images/dongtai12.png',
        ],
        mediaType: 'image',
        thumbnailUrls: [],
        createdAt: DateTime.now().subtract(const Duration(hours: 24)),
        likes: ['1', '2', '3', '4', '5', '6', '7', '9', '10'],
        comments: [
          DynamicComment(
            id: '11',
            userId: '9',
            content: 'I see peace and tranquility! Beautiful shot!',
            createdAt: DateTime.now().subtract(const Duration(hours: 22)),
          ),
          DynamicComment(
            id: '12',
            userId: '10',
            content: 'The reflection is perfect! Nature is amazing.',
            createdAt: DateTime.now().subtract(const Duration(hours: 20)),
          ),
          DynamicComment(
            id: '13',
            userId: '1',
            content: 'This is why I love lakes so much!',
            createdAt: DateTime.now().subtract(const Duration(hours: 18)),
          ),
        ],
      ),

      DynamicPrint(
        id: '9',
        userId: '9', // waterpeace用户
        title: 'Little Joys by the Lake',
        content:
            'The lake stays calm, just like my mood right now: wind blows gently, I stay quiet, and everything feels perfect.',
        mediaUrls: [
          'assets/images/dongtai13.png',
          'assets/images/dongtai14.png',
        ],
        mediaType: 'image',
        thumbnailUrls: [],
        createdAt: DateTime.now().subtract(const Duration(hours: 24)),
        likes: ['1', '2', '3', '4', '5', '6', '7', '9', '10'],
        comments: [
          DynamicComment(
            id: '11',
            userId: '9',
            content: 'I see peace and tranquility! Beautiful shot!',
            createdAt: DateTime.now().subtract(const Duration(hours: 22)),
          ),
          DynamicComment(
            id: '12',
            userId: '10',
            content: 'The reflection is perfect! Nature is amazing.',
            createdAt: DateTime.now().subtract(const Duration(hours: 20)),
          ),
          DynamicComment(
            id: '13',
            userId: '1',
            content: 'This is why I love lakes so much!',
            createdAt: DateTime.now().subtract(const Duration(hours: 18)),
          ),
        ],
      ),
    ]);
  }

  /// 获取所有动态
  List<DynamicPrint> fetchAllDynamics() {
    // 如果数据为空，自动初始化默认数据
    if (dynamics.isEmpty) {
      initializeDefaultDynamics();
    }
    return List.from(dynamics);
  }

  /// 根据ID获取动态
  DynamicPrint? fetchDynamicById(String id) {
    try {
      return dynamics.firstWhere((dynamic) => dynamic.id == id);
    } catch (e) {
      return null;
    }
  }

  /// 根据用户ID获取动态
  List<DynamicPrint> fetchDynamicsByUserId(String userId) {
    return dynamics.where((dynamic) => dynamic.userId == userId).toList();
  }

  /// 发布新动态
  @action
  bool publishDynamic({
    required String userId,
    required String title,
    required String content,
    required List<String> mediaUrls,
    required String mediaType,
    required List<String?> thumbnailUrls,
  }) {
    try {
      final newDynamic = DynamicPrint(
        id: (dynamics.length + 1).toString(),
        userId: userId,
        title: title,
        content: content,
        mediaUrls: mediaUrls,
        mediaType: mediaType,
        thumbnailUrls: thumbnailUrls,
        createdAt: DateTime.now(),
        likes: [],
        comments: [],
      );
      dynamics.insert(0, newDynamic); // 插入到列表开头
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 点赞/取消点赞动态
  @action
  bool toggleLike(String dynamicId, String userId) {
    try {
      final index = dynamics.indexWhere((dynamic) => dynamic.id == dynamicId);
      if (index != -1) {
        final dynamic = dynamics[index];
        final likes = List<String>.from(dynamic.likes);

        if (likes.contains(userId)) {
          likes.remove(userId);
        } else {
          likes.add(userId);
        }

        final updatedDynamic = DynamicPrint(
          id: dynamic.id,
          userId: dynamic.userId,
          title: dynamic.title,
          content: dynamic.content,
          mediaUrls: dynamic.mediaUrls,
          mediaType: dynamic.mediaType,
          thumbnailUrls: dynamic.thumbnailUrls,
          createdAt: dynamic.createdAt,
          likes: likes,
          comments: dynamic.comments,
        );

        dynamics[index] = updatedDynamic;
        return true;
      }
      return false;
    } catch (e) {
      return false;
    }
  }

  /// 添加评论
  @action
  bool addComment(String dynamicId, String userId, String content) {
    try {
      final index = dynamics.indexWhere((dynamic) => dynamic.id == dynamicId);
      if (index != -1) {
        final dynamic = dynamics[index];
        final comments = List<DynamicComment>.from(dynamic.comments);

        final newComment = DynamicComment(
          id: '${DateTime.now().millisecondsSinceEpoch}',
          userId: userId,
          content: content,
          createdAt: DateTime.now(),
        );

        comments.add(newComment);

        final updatedDynamic = DynamicPrint(
          id: dynamic.id,
          userId: dynamic.userId,
          title: dynamic.title,
          content: dynamic.content,
          mediaUrls: dynamic.mediaUrls,
          mediaType: dynamic.mediaType,
          thumbnailUrls: dynamic.thumbnailUrls,
          createdAt: dynamic.createdAt,
          likes: dynamic.likes,
          comments: comments,
        );

        dynamics[index] = updatedDynamic;
        return true;
      }
      return false;
    } catch (e) {
      return false;
    }
  }

  /// 删除动态
  @action
  bool deleteDynamic(String id) {
    try {
      dynamics.removeWhere((dynamic) => dynamic.id == id);
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 获取动态总数
  int get dynamicCount => dynamics.length;

  /// 检查用户是否已点赞
  bool isLikedByUser(String dynamicId, String userId) {
    final dynamic = fetchDynamicById(dynamicId);
    return dynamic?.likes.contains(userId) ?? false;
  }

  /// 获取动态点赞数
  int getLikeCount(String dynamicId) {
    final dynamic = fetchDynamicById(dynamicId);
    return dynamic?.likes.length ?? 0;
  }

  /// 获取动态评论数
  int getCommentCount(String dynamicId) {
    final dynamic = fetchDynamicById(dynamicId);
    return dynamic?.comments.length ?? 0;
  }

  /// 删除评论
  @action
  bool deleteComment(String dynamicId, String commentId) {
    try {
      final index = dynamics.indexWhere((dynamic) => dynamic.id == dynamicId);
      if (index != -1) {
        final dynamic = dynamics[index];
        final comments = List<DynamicComment>.from(dynamic.comments);

        comments.removeWhere((comment) => comment.id == commentId);

        final updatedDynamic = DynamicPrint(
          id: dynamic.id,
          userId: dynamic.userId,
          title: dynamic.title,
          content: dynamic.content,
          mediaUrls: dynamic.mediaUrls,
          mediaType: dynamic.mediaType,
          thumbnailUrls: dynamic.thumbnailUrls,
          createdAt: dynamic.createdAt,
          likes: dynamic.likes,
          comments: comments,
        );

        dynamics[index] = updatedDynamic;
        return true;
      }
      return false;
    } catch (e) {
      return false;
    }
  }
}
